/**
 * Anderground project - Subway maps processor application.
 * Copyright (C) 2008-2009 Eldar Abusalimov, Ilya Shurigyn
 * 
 * This file is part of Anderground.
 * 
 * Anderground is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Anderground is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Anderground.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.anderground.core.model;

import java.io.Serializable;

import org.anderground.core.util.Bindable;
import org.anderground.core.util.Binder;
import org.anderground.core.util.BindingException;

/**
 * Transfer class
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
public class Transfer extends Transition implements Serializable {

	/**
	 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
	 */
	public final class Editor extends Transition.Editor {

		/**
		 * private constructor
		 */
		private Editor() {
		}

	}

	private static final long serialVersionUID = -2197493586342517597L;

	/** the Hub part of which this transfer is */
	transient private Hub hub;

	transient private Editor editor;

	/**
	 * @param fromStation
	 * @param toStation
	 * @param time
	 *            - time between fromStation and toStation in seconds
	 */
	public Transfer(Station fromStation, Station toStation, int time) {
		super(fromStation, toStation, time);
	}

	@Override
	protected void onUnbindFrom(Binder binder) throws BindingException {
		if (this.hub != null) {
			this.hub.unbindFrom(binder);
		}
		super.onUnbindFrom(binder);
	}

	@Override
	protected void onBindWith(Bindable bindable) throws BindingException {
		if (bindable instanceof Hub) {
			Hub hub = (Hub) bindable;
			if (this.hub != null) {
				throw new BindingException("transfer " + this
						+ " has already got a hub");
			}
			this.hub = hub;
		}
	}

	@Override
	protected void onUnbindWith(Bindable bindable) throws BindingException {
		if (bindable instanceof Hub) {
			Hub hub = (Hub) bindable;
			if (this.hub != hub) {
				throw new BindingException("transfer " + this
						+ " has got another hub");
			}
			this.hub = null;
		}
	}

	/**
	 * @return the hub
	 */
	public Hub getHub() {
		if (isBound()) {
			getBinder().ensureConsistency();
			return hub;
		} else {
			return null;
		}
	}

	/**
	 * @return
	 */
	@Override
	Editor getEditor() {
		if (editor == null) {
			editor = new Editor();
		}

		return editor;
	}

}
